<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-card>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>

        <el-form-item label="报关单号">
          <el-input
            v-model="queryParams.customsNo"
            placeholder="请输入报关单号"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item label="许可证号">
          <el-input
            v-model="queryParams.licenseNo"
            placeholder="请输入许可证号"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="品名">
          <el-input
            v-model="queryParams.rawMaterial"
            placeholder="请输入品名"
            clearable
            @keydown.enter.prevent="handleQuery"
          />
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card class="mt20">
      <el-row justify="space-between" class="mb10">
        <span style="font-size: 18px">下脚料记录</span>
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新增下脚料</el-button
        >
      </el-row>

      <el-table :data="inFeedList" border stripe v-loading="loading">
        <el-table-column prop="collectTime" label="收集时间" />
        <el-table-column prop="collectAmount" label="收集数量" />
        <el-table-column label="称重照片">
          <template #default="{ row }">
            <el-image
              style="width: 60px; height: 60px"
              :src="row.weightPic"
              fit="cover"
              @click="previewImage(row.weightPic)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="processingTime" label="处理时间" />
        <el-table-column prop="processingAmount" label="处理数量" />
        <el-table-column label="焚烧照片">
          <template #default="{ row }">
            <el-image
              style="width: 60px; height: 60px"
              :src="row.burningPic"
              fit="cover"
              @click="previewImage(row.burningPic)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="customsNo" label="报关单号" />
        <el-table-column prop="transferNo" label="调运单号" />
        <el-table-column prop="licenseNo" label="许可证号" />
        <el-table-column prop="curChargePerson" label="负责人" />

        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewDetail(row)"
              >编辑</el-button
            >
            <el-button link type="danger" @click="deleteRow(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? '编辑下脚料' : '新增下脚料'"
      width="600px"
    >
      <el-form :model="formData" label-width="120px">
        <el-form-item label="收集时间">
          <el-date-picker
            v-model="formData.collectTime"
            type="date"
            placeholder="请选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="收集数量">
          <el-input-number v-model="formData.collectAmount" :min="0" />
        </el-form-item>
        <el-form-item label="称重照片">
          <el-upload
            class="upload-demo"
            action="/dev-api/minio/upload"
            :on-success="handleWeightPicSuccess"
            :on-remove="handleWeightPicRemove"
            :file-list="formData.weightPicList"
            :limit="1"
            list-type="picture-card"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="处理时间">
          <el-date-picker
            v-model="formData.processingTime"
            type="date"
            placeholder="请选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="处理数量">
          <el-input-number v-model="formData.processingAmount" :min="0" />
        </el-form-item>
        <el-form-item label="焚烧照片">
          <el-upload
            class="upload-demo"
            action="/dev-api/minio/upload"
            :on-success="handleBurningPicSuccess"
            :on-remove="handleBurningPicRemove"
            :file-list="formData.burningPicList"
            :limit="1"
            list-type="picture-card"
            :headers="headers"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="报关单号">
          <el-input v-model="formData.customsNo" />
        </el-form-item>
        <el-form-item label="调运单号">
          <el-input v-model="formData.transferNo" />
        </el-form-item>
        <el-form-item label="许可证号">
          <el-input v-model="formData.licenseNo" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="formData.curChargePerson" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showImageViewer"
      :url-list="[imagePreviewUrl]"
      @close="showImageViewer = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { xList, xAdd, xEdit, xDelete } from "@/api/wms/operation";
import { getToken } from "@/utils/auth";

const loading = ref(false);
const total = ref(0);
// 日期范围
const dateRange = ref([]); // [start, end]
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  customsNo: "",
  licenseNo: "",
  rawMaterial: "",
  collectStartTime: "",
  collectEndTime: ""
});

const headers = ref({ Authorization: "Bearer " + getToken() });
const inFeedList = ref([]);
const showImageViewer = ref(false);
const imagePreviewUrl = ref("");

function previewImage(url) {
  imagePreviewUrl.value = url;
  showImageViewer.value = true;
}

async function handleQuery() {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.collectStartTime = dateRange.value[0];
    queryParams.collectEndTime = dateRange.value[1];
  } else {
    queryParams.collectStartTime = "";
    queryParams.collectEndTime = "";
  }
  loading.value = true;
  try {
    const res = await xList(queryParams);
    inFeedList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (err) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
}

function resetQuery() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    customsNo: "",
    licenseNo: "",
    rawMaterial: "",
    collectStartTime: "",
    collectEndTime: ""
  });
  dateRange.value = [];
  handleQuery();
}

const dialogVisible = ref(false);

const formData = reactive({
  id: null,
  collectTime: "",
  collectAmount: "",
  weightPic: "",
  weightPicList: [],
  processingTime: "",
  processingAmount: "",
  burningPic: "",
  burningPicList: [],
  customsNo: "",
  transferNo: "",
  licenseNo: "",
  curChargePerson: "",
});

function handleWeightPicSuccess(res, file, fileList) {
  formData.weightPicList = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
  formData.weightPic = fileList[0]?.response?.msg || "";
}

function handleWeightPicRemove(file, fileList) {
  formData.weightPicList = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
  formData.weightPic = fileList[0]?.response?.msg || "";
}

function handleBurningPicSuccess(res, file, fileList) {
  formData.burningPicList = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
  formData.burningPic = fileList[0]?.response?.msg || "";
}

function handleBurningPicRemove(file, fileList) {
  formData.burningPicList = fileList.map((f) => ({
    name: f.name,
    url: f.response?.msg || f.url,
  }));
  formData.burningPic = fileList[0]?.response?.msg || "";
}

function handleAdd() {
  resetForm();
  dialogVisible.value = true;
}

function viewDetail(row) {
  Object.assign(formData, {
    ...row,
    weightPicList: row.weightPic ? [{ name: "图片", url: row.weightPic }] : [],
    burningPicList: row.burningPic
      ? [{ name: "图片", url: row.burningPic }]
      : [],
  });
  dialogVisible.value = true;
}

function resetForm() {
  Object.assign(formData, {
    id: null,
    collectTime: "",
    collectAmount: "",
    weightPic: "",
    weightPicList: [],
    processingTime: "",
    processingAmount: "",
    burningPic: "",
    burningPicList: [],
    customsNo: "",
    transferNo: "",
    licenseNo: "",
    curChargePerson: "",
  });
}

async function submitForm() {
  if (formData.id) {
    await xEdit(formData);
    ElMessage.success("编辑成功");
  } else {
    await xAdd(formData);
    ElMessage.success("新增成功");
  }
  dialogVisible.value = false;
  handleQuery();
}

function deleteRow(row) {
  ElMessageBox.confirm("确定删除该条记录吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      await xDelete(row.id);
      ElMessage.success("删除成功");
      handleQuery();
    })
    .catch(() => {});
}

onMounted(() => {
  handleQuery();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mt20 {
  margin-top: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
